package net.starwifi.duobao.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/3/8.
 */
public class AESCrypto {

    public static final String ALG = "AES";
    public static final String CRYPTO_MODE_PAD = "AES/CBC/PKCS5Padding";
    public static final String IV = "0000000000000000";

    public static String decrypt(String data, String key) throws Exception {
        Cipher c = Cipher.getInstance(CRYPTO_MODE_PAD);
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), ALG);
        IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes());
        c.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] decodedValue = Base64.decodeBase64(data.getBytes());
        byte[] decryptedVal = c.doFinal(decodedValue);
        return new String(decryptedVal, "UTF-8");

    }

    public static String encrypt(String data, String key) throws Exception {
        Cipher c = Cipher.getInstance(CRYPTO_MODE_PAD);
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), ALG);
        IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes());
        c.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        byte[] results = c.doFinal(data.getBytes("UTF-8"));
        return Base64.encodeBase64String(results).replaceAll("\r\n", "");
    }

    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws Exception {
        String key = "5cfa5dbf63d24647";
        String v = "18671725223";
        String ev = URLEncoder.encode(AESCrypto.encrypt(v, key));
        System.out.println(ev);
        try {
            HttpRequester request = new HttpRequester();
            request.setDefaultContentEncoding("utf-8");
            String Url = "http://i.wo.com.cn/zq/woplus/credit/home";
            Map<String, String> params = new HashMap<String, String>();
            params.put("pm", ev);
            HttpRespons hr = request.sendGet(Url, params);
            System.out.println(hr.getUrlString());
            System.out.println(hr.getProtocol());
            System.out.println(hr.getHost());
            System.out.println(hr.getPort());
            System.out.println(hr.getContentEncoding());
            System.out.println(hr.getMethod());

            System.out.println(hr.getContent());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
